package com.bhald.CJ.MethodView;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.os.Environment;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.LinearLayout;

import com.androidquery.AQuery;
import com.bhald.CJ.Adapter.GatewayAdapter;
import com.bhald.CJ.Cache.BufferStore;
import com.bhald.CJ.Common.Common;
import com.bhald.CJ.Common.CommonM;
import com.bhald.CJ.Common.CommonaddView;
import com.bhald.CJ.Entity.AddGateway;
import com.bhald.CJ.lock.R;

public class SetLayout_Gateway {

	/*
	 * Gateway
	 */

	private LinearLayout Gatewaylayout;
	private AQuery query;
	private Activity context;
	private Button set_layout_addgateway;
	private View gateway_layout;
	private List<AddGateway> listaddGate = null;

	//
	public SetLayout_Gateway(LinearLayout Gatewaylayout, Activity context,
			Button set_layout_addgateway) {
		this.set_layout_addgateway = set_layout_addgateway;
		this.Gatewaylayout = Gatewaylayout;
		this.context = context;
		query = new AQuery(context);
	}

	public void Start() {
		gateway_layout = CommonaddView.addView(Gatewaylayout, context,
				R.layout.set_layout_main_gateway_list);

		//
		CreateLock();
	}

	public void CreateLock() {
		String LockFile = Environment.getExternalStorageDirectory().toString()
				+ "/" + Common.FILENAME + "/" + Common.GATEWAY;
		if (CommonM.CheckSD()) {
			CommonM.CreateLockFile(LockFile);
		}

		// String[] str = new File(LockFile).list();
		File[] file = new File(LockFile).listFiles();

		listaddGate = new ArrayList<AddGateway>();
		for (int i = 0; i < file.length; i++) {
			List<AddGateway> list = new ArrayList<AddGateway>();

			BufferStore<AddGateway> store = new BufferStore<AddGateway>(
					file[i].toString());
			list = store.read();

			AddGateway gateway = new AddGateway();
			gateway.setGatewayname(list.get(0).getGatewayname());
			gateway.setGatewaynums(list.get(0).getGatewaynums());
			gateway.setMsggeneral(list.get(0).getMsggeneral());
			gateway.setMsgpolice(list.get(0).getMsgpolice());
			listaddGate.add(gateway);
		}

		GatewayAdapter adapter = new GatewayAdapter(listaddGate, context);
		query.id(
				gateway_layout
						.findViewById(R.id.set_layout_main_gateway_listview))
				.adapter(adapter).itemClicked(new OnItemClickListener() {

					@Override
					public void onItemClick(AdapterView<?> arg0, View arg1,
							int arg2, long arg3) {

						set_layout_addgateway.setVisibility(4);
						//
						SetLayout_AddGateway addGateway = new SetLayout_AddGateway(
								Gatewaylayout, context, listaddGate.get(arg2),
								Common.VAILDN);
						addGateway.Start();

					}
				});

	}
}
